package com.ruoyi.business.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.business.domain.Product;
import com.ruoyi.business.domain.User;
import com.ruoyi.business.domain.UserProduct;
import com.ruoyi.business.domain.vo.ShoppingCarVo;
import com.ruoyi.business.mapper.ProductMapper;
import com.ruoyi.business.mapper.UserMapper;
import com.ruoyi.business.mapper.UserProductMapper;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.ShoppingCarMapper;
import com.ruoyi.business.domain.ShoppingCar;
import com.ruoyi.business.service.IShoppingCarService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import sun.nio.cs.US_ASCII;

/**
 * 购物车Service业务层处理
 * 
 * @author 吴倩芸
 * @date 2023-03-07
 */
@SuppressWarnings("ALL")
@Service
public class ShoppingCarServiceImpl extends ServiceImpl<ShoppingCarMapper, ShoppingCar> implements IShoppingCarService
{
    @Autowired
    private ShoppingCarMapper shoppingCarMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private UserProductMapper userProductMapper;

    /**
     * 查询购物车
     * 
     * @param id 购物车主键
     * @return 购物车
     */
    @Override
    public ShoppingCar selectShoppingCarById(Long id)
    {
        return shoppingCarMapper.selectShoppingCarById(id);
    }

    /**
     * 查询购物车列表
     * 
     * @param shoppingCar 购物车
     * @return 购物车
     */
    @Override
    public List<ShoppingCarVo> selectShoppingCarList(ShoppingCar shoppingCar)
    {
        Long userId = SecurityUtils.getUserId();
        if (!SecurityUtils.isAdmin(userId)) {
            shoppingCar.setUserId(userId);
        }
        List<ShoppingCar> list = shoppingCarMapper.selectShoppingCarList(shoppingCar);
        return list.stream().map(item -> {
            ShoppingCarVo vo = new ShoppingCarVo();
            BeanUtils.copyProperties(item, vo);
            vo.setProduct(productMapper.selectProductById(item.getProductId()));
            vo.setUser(userMapper.selectUserById(item.getUserId()));
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 新增购物车
     * 
     * @param shoppingCar 购物车
     * @return 结果
     */
    @Transactional
    @Override
    public int insertShoppingCar(ShoppingCar shoppingCar)
    {
        Long userId = SecurityUtils.getUserId();
        // 设置本次购买的用户id
        shoppingCar.setUserId(userId);
        if (null == shoppingCar.getUserId()) {
            shoppingCar.setUserId(userId);
        }
        // 设置本次新增的购物车价值
        Product product = productMapper.selectProductById(shoppingCar.getProductId());
        shoppingCar.setWorth(Double.parseDouble(product.getWorth()) * shoppingCar.getNum());
        // 设置添加购物车的日期
        shoppingCar.setAddTime(new Date());
        return shoppingCarMapper.insertShoppingCar(shoppingCar);
    }

    /**
     * 修改购物车
     * 
     * @param shoppingCar 购物车
     * @return 结果
     */
    @Override
    public int updateShoppingCar(ShoppingCar shoppingCar)
    {
        return shoppingCarMapper.updateShoppingCar(shoppingCar);
    }

    /**
     * 批量删除购物车
     * 
     * @param ids 需要删除的购物车主键
     * @return 结果
     */
    @Override
    public int deleteShoppingCarByIds(Long[] ids)
    {
        return shoppingCarMapper.deleteShoppingCarByIds(ids);
    }

    /**
     * 删除购物车信息
     * 
     * @param id 购物车主键
     * @return 结果
     */
    @Override
    public int deleteShoppingCarById(Long id)
    {
        return shoppingCarMapper.deleteShoppingCarById(id);
    }

    @Transactional
    @Override
    public int clearShoppingCar(List<ShoppingCar> list) {
        // 用户购买产品的列表
        List<UserProduct> userProducts = new ArrayList<>();
        Long[] shoppingCarIds = new Long[list.size()];
        Double totalPrice = new Double(0);
        // 获取当下的用户信息
        Long userId = SecurityUtils.getUserId();
        User user = userMapper.selectUserById(userId);
        for (int i = 0; i < list.size(); i++) {
            ShoppingCar item = list.get(i);
            totalPrice += item.getWorth();
            UserProduct userProduct = new UserProduct();
            userProduct.setUserId(userId);
            userProduct.setAmount(item.getWorth());
            userProduct.setProductId(item.getProductId());
            userProduct.setBuyNum(item.getNum());
            userProduct.setBuyTime(new Date());
            userProducts.add(userProduct);
            shoppingCarIds[i] = item.getId();
        }
        // 用户的余额
        Double restMoney = Double.parseDouble(user.getMoney());
        if (totalPrice > restMoney) {
            throw new RuntimeException("对不起，您当下余额不足，请充值之后重新购买");
        }
        restMoney -= totalPrice;
        user.setMoney(Double.toString(restMoney));
        // 扣除用户余额
        userMapper.updateUser(user);
        // 删除购物车的记录
        shoppingCarMapper.deleteShoppingCarByIds(shoppingCarIds);
        // 新增用户购买记录
        userProductMapper.insertUserProducts(userProducts);
        return list.size();
    }
}
